package org.theSeed.springBase.pojo.prop;

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.theSeed.base.pojo.config.NameThreadFactory;

import java.util.concurrent.*;

@Getter
@Setter
public class SpringExecutorProp {
    /**
     * 设置线程池中的核心线程数(最小线程数)
     */
    private Integer corePoolSize = Runtime.getRuntime().availableProcessors();

    /**
     * 设置线程池中的最大线程数
     */
    private Integer maxPoolSize = Double.valueOf(Math.floor(Runtime.getRuntime().availableProcessors() * 1.5)).intValue();

    /**
     * 设置线程池中任务队列的容量
     */
    private Integer queueCapacity = 10;

    /**
     * 设置线程池中空闲线程的存活时间
     */
    private Integer keepAliveSeconds = 20;

    /**
     * 设置线程池关闭时等待所有任务完成的时间
     */
    private Integer awaitTerminationSeconds = 60;

    /**
     * 设置线程池在关闭时是否等待所有任务完成
     */
    private Boolean allowCoreThreadTimeOut = true;

    /**
     * 创建spring线程池
     * @return
     */
    public Executor createThreadPoolTaskExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        threadPoolTaskExecutor.setKeepAliveSeconds(keepAliveSeconds);
        threadPoolTaskExecutor.setAwaitTerminationSeconds(awaitTerminationSeconds);
        threadPoolTaskExecutor.setAllowCoreThreadTimeOut(allowCoreThreadTimeOut);
        threadPoolTaskExecutor.setThreadNamePrefix(NameThreadFactory.getDefaultThreadFactory().getNamePrefix());
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolTaskExecutor;
    }
}
